import typing
import os
from fastapi import Depends
from sqlalchemy import select, Result
from sqlalchemy.ext.asyncio import (
    create_async_engine,
    async_sessionmaker,
    AsyncSession,
    AsyncAttrs,
)
from sqlalchemy.orm import DeclarativeBase

from scaner.core.models.tg_chat_reference import TgChatReference


BASE_DIR = os.path.dirname(__file__).rsplit(os.path.sep, 2)[0]
DB_PATH = f"{BASE_DIR}/scaner/scan.db"
DB_URL = f"sqlite+aiosqlite:///{DB_PATH}"


class Base(AsyncAttrs, DeclarativeBase):
    pass


async def get_async_session(db_url: str = DB_URL) -> AsyncSession:
    engine = create_async_engine(db_url)
    async_session_maker = async_sessionmaker(
        engine,
        class_=AsyncSession,
        expire_on_commit=False,
    )
    async with async_session_maker() as session:
        return session


async def get_token_by_chat_id(chat_id: int) -> str | None:

    session: AsyncSession = await get_async_session()
    stmt = select(TgChatReference).where(TgChatReference.chat_id == chat_id)

    result: Result = await session.execute(stmt)
    reference: TgChatReference | None = result.scalar_one_or_none()

    return reference.token if reference else None
